<?php
//ini_set('display_errors', 1);
//ini_set("log_errors", 1);
//error_reporting(1);
ini_set("error_log", "php-error.log");

/* this file handles some actions that are most of the time requested 
   by the javascript portion of the FE */

/* since most of the time the file is loaded sandalonely, so we have to 
   include the initializing files if they haven't been included already */
require_once "vendor/simple_html_dom.php";
require_once "settings.php";
require_once "include/init.php";
require_once "include/functions.php";

$srv = $user_settings['instance'];

if (isset($_POST['action']) && $_POST['action'] == "settings"){
	if(!empty($_FILES["avatar"]["name"])){
		$ext = strtolower(end(explode('.', $_FILES["avatar"]['name'])));
		if(in_array($ext,array("jpg","jpeg","gif","png"))){
			$file_name = time().mt_rand(100,199).".".$ext;
			$file_tmp = $_FILES["avatar"]['tmp_name'];
			move_uploaded_file($file_tmp, $file_name);
			upload_profile($file_name,'avatar');
			unlink($file_name);	
		} else {
			unlink($_FILES["avatar"]['tmp_name']);	
		}
	}
	if(!empty($_FILES["header"]["name"])){
		$ext = strtolower(end(explode('.', $_FILES["header"]['name'])));
		if(in_array($ext,array("jpg","jpeg","gif","png"))){
			$file_name = time().mt_rand(100,199).".".$ext;
			$file_tmp = $_FILES["header"]['tmp_name'];
			move_uploaded_file($file_tmp, $file_name);
			upload_profile($file_name,'header');
			unlink($file_name);	
		} else {
			unlink($_FILES["header"]['tmp_name']);	
		}
	}
	foreach($_POST as $key => $value){
		switch($key){
			case "username":
				api_patch("accounts/update_credentials",array('display_name'=>$value));
				break;
			
			case "bio":
				api_patch("accounts/update_credentials",array('note'=>$value));
				break;
			
			case "explicit":
				$user_settings['explicit'] = htmlentities($value);
				break;
				
			case "emoji":
				$user_settings['emoji'] = intval($value);
				break;
				
			case "defscope":
				$user_settings['defscope'] = intval($value);
				break;
				
			case "text":
				$user_settings['text'] = ($value == "on" ? "on" : "off");
				break;
				
			case "attach":
				$user_settings['attach'] = ($value == "on" ? "on" : "off");
				break;
				
			case "replies":
				$user_settings['replies'] = ($value == "on" ? "on" : "off");
				break;
				
			
			case "reblog":
				$user_settings['reblog'] = ($value == "on" ? "on" : "off");
				break;

			case "videoloop":
				$user_settings['videoloop'] = ($value == "on" ? "on" : "off");
				break;	
			
			case "theme":
				$user_settings['theme'] = sanitize($value);
				break;	
			
			case "instance":
				if (!isset($_COOKIE['token'])){
					$user_settings['instance'] = htmlentities($value);
				}
				break;
				
			case "mtwords":
				$user_settings['mtwords'] = array();
				$mtwords = explode("\n",$value);
				foreach ($mtwords as $word){
					$user_settings['mtwords'][] = sanitize($word);
				}
				break;
				
			case "fhtags":
				$user_settings['fhtags'] = array();
				$fhtags = explode("\n",$value);
				foreach ($fhtags as $word){
					$user_settings['fhtags'][] = sanitize($word);
				}
				break;
				
			case "fg":
				$theme['fg'] = sanitize($value);
				break;
				
			case "bg":
				$theme['bg'] = sanitize($value);
				break;
				
			case "tx":
				$theme['tx'] = sanitize($value);
				break;
			
			case "lc":
				$theme['lc'] = sanitize($value);
				break;

			case "bc":
				$theme['bc'] = sanitize($value);
				break;

			case "br":
				$theme['br'] = sanitize($value);
				break;

			case "bw":
				$theme['bw'] = sanitize($value);
				break;					
		}
	}
	setrawcookie("user_settings",base64_encode(json_encode($user_settings)),time()+60*60*24*30,'/'); 
	setrawcookie("theme",base64_encode(json_encode($theme)),time()+60*60*24*30,'/'); 
	header("location: ./?page=settings");
}


$thread = (isset($_GET['thread']) ? htmlentities($_GET['thread']) : false);
$mode = (isset($_GET['mode']) ? htmlentities($_GET['mode']) : false);
$ajax = (isset($_GET['a']) ? true : false);

foreach($_GET as $key => $value){
	switch($key){
		case "vote":
			$elem = array();
			$elem['poll'] = json_decode(vote($value,$_GET['choices']),true);
			//var_dump($_GET['choices']);
			echo renderPoll($elem);
			break;
		
		case "fav":
			$result = favourite($value,($mode === 'on' ? true : false));
			if ($ajax){
				echo $result;
				die();
			} else {
				header("Location: ?thread=".$value);
			}
			break;
			
		case "reblog":
			$result =reblog($value,($mode === 'on' ? true : false));
			if ($ajax){
				echo $result;
				die();
			} else {
				header("Location: ?thread=".$value);
			}
			break;
			
		case "mute":
			if($thread){
				$rel = api_post("statuses/".htmlentities($value)."/".($mode === 'true' ? "" : "un")."mute",array());
				echo (isset($rel[0]['muting']) ? "1" : "0" );
			} else {
				$rel = api_post("accounts/".htmlentities($value)."/".($mode === 'true' ? "" : "un")."mute",array());
				echo (isset($rel[0]['muting']) ? "1" : "0" );
			}
			die();
			break;
			
		case "list":
			if($mode === 'true'){
				$rel = api_post("lists/".htmlentities($value)."/accounts?account_ids[]=".$_GET['user'],array());
				var_dump($rel);
			} else {
				$rel = api_delete("lists/".htmlentities($value)."/accounts?account_ids[]=".$_GET['user'],array());
				var_dump($rel);
			}
			die();
			break;
			
		case "block":
			$rel = api_post("accounts/".htmlentities($value)."/".($mode === 'true' ? "" : "un")."block",array());
			echo (isset($rel[0]['blocking']) ? "1" : "0" );
			die();
			break;
	
		case "bookmark":
			$status = api_get("statuses/".htmlentities($value));
			$rel = api_post("statuses/".htmlentities($value)."/".($status['bookmarked'] == 'true' ? "un" : "")."bookmark",array());
			die();
			break;					
			
		case "notif":
			
			echo getnotif(intval($value),(isset($_GET['max']) ? true : false));
			die();
			break;
			
		case "delete":
			echo delpost(htmlentities($value));
			die();
			break;
			
		case "replies":
			$since = (isset($_GET['since']) ? htmlentities($_GET['since']) : false);
			foreach(getreplies(htmlentities($value),$since) as $elem){
				echo render_reply($elem['content']);
			}
			die();
			break;
			
		case "notes":
			$notes = getnotes($value);
			foreach ($notes as $note){
				echo "<div id='".$note[1]['id']."'>
						<a href='?user=".$note[1]['id']."' class='ldr' title='".$note[1]['acct']."'>
							<div class='nte' style='background-image:url(".$note[1]['avatar'].");'>
								<div class='nte_type' style='background-color:".($note[0] == "fav" ? "red" : "green")."'><span>".($note[0] == "fav" ? "&#xe802;" : "&#xe826;")."</span></div>
							</div>
						</a>
					  </div>";	
			}
			die();
			break;
			
		case "follow":
			$rel = api_post("accounts/".htmlentities($value)."/follow",array());
			echo ($rel['following'] == true || $rel['requested'] == true ? "1" : "0" );
			die();
			break;
			
		case "unfollow":
			$rel = api_post("accounts/".htmlentities($value)."/unfollow",array());
			echo ($rel['following'] == false ? "1" : "0" );
			die();
			break;
			
		case "nsfw":
			if(in_array($value,$user_settings['nsfw'])){
				$key = array_search($value, $user_settings['nsfw']);
				unset($user_settings['nsfw'][$key]);
				setrawcookie("user_settings",base64_encode(json_encode($user_settings)),time()+60*60*24*30,'/'); 
			} else {
				$user_settings['nsfw'][] = htmlentities($value);
				setrawcookie("user_settings",base64_encode(json_encode($user_settings)),time()+60*60*24*30,'/'); 
			}
			echo "1";
			die();
			break;
			
		case "hide":
			if(!isset($user_settings['hide'])|| !is_array($user_settings['hide'])){
				$user_settings['hide'] = array();
			}
			if(in_array($value,$user_settings['hide'])){
				$key = array_search($value, $user_settings['hide']);
				unset($user_settings['hide'][$key]);
				setrawcookie("user_settings",base64_encode(json_encode($user_settings)),time()+60*60*24*30,'/'); 
			} else {
				$user_settings['hide'][] = htmlentities($value);
				setrawcookie("user_settings",base64_encode(json_encode($user_settings)),time()+60*60*24*30,'/'); 
			}
			echo "1";
			die();
			break;
			
		case "userinfo":
			$info = api_get("accounts/".htmlentities($value));
			$rel = api_get("accounts/relationships?id=".htmlentities($value));
			/*
			$photos = api_get("accounts/".htmlentities($value)."/statuses?only_media=true&limit=5&exclude_reblogs=true");
			$photo = array();
			$c = 0;
			if (!empty($photos)){
				foreach ($photos as $elem){
					if ($elem['media_attachments'][0]['type'] == "image"){
						$photo[$c]['url'] = $elem['media_attachments'][0]['url'];
						if ($elem['sensitive'] == true){
							$photo[$c]['s'] = true;
						}
						$c++;

					}
					if ($c == 3){
						break;
					}
				}
			}
			*/
			
			echo "<div class='userinfo_he' style='background-color:#".averageColor($info['avatar'])."; background-size:cover;" . (!empty($info['header']) ? "background-image:url(".$info['header'].");" : "") . "'>
					<span style='margin:5px; display:inline-block;'>
						<a href='".$info['url']."' target='_blank' class='external' style='font-weight:bold; font-size:13px; text-decoration:none; color: white; text-shadow: -1px -1px 0 #000,  1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;'>".$info['acct']."</a>
					</span>
				  </div>
					<div class='userinfo_co'>
						<div class='avatar' style='position: absolute; left:35%; top:-60px; display:inline-block; margin:0px; background-color:white; background-image:url(" . $info['avatar'] . "); text-align:center; border:3px solid white; border-radius:10px; clear:both;'></div>
						<div style='font-weight:bold; padding-top:30px; display:block;'><a href='?user=".$info['id']."' class='link ldr' style='font-size:15px;'>".emojify($info['display_name'],$info['emojis'],20)."</a></div><br>
						<div style='font-weight:normal; font-size:12px; line-height:12px;'>".emojify($info['note'],$info['emojis'],20)."</div><br>
						<span style='width:290; height:30px; display:block; margin-top:10px;'>
							".($logedin ? "<span id='".$info['id']."' class='profileButton ".(($rel[0]['following'] || $rel[0]['requested']) ? "unfollow" : "follow" )."'>".($rel[0]['following'] || $rel[0]['requested'] ? "Following" : "Follow" )."</span>" : "")."
							<span id='".$info['id']."' class='profileButton ".(in_array($info['id'],$user_settings['nsfw']) ? "unnsfw" : "nsfw" )."'>".(in_array($info['id'],$user_settings['nsfw']) ? "NSFW <span class='fontello'>&#xf205;</span>" : "NSFW <span class='fontello'>&#xf204;</span>" )."</span>
							".($logedin ? "<span id='" . $info['id'] . "' class='profileButton " . ($rel[0]['muting'] ? "un" : "") . "mute'>" . ($rel[0]['muting'] ? "&#xe81a; Unmute" : "&#xe81b; Mute") . "</span>" : "")."<br>
						</span>
							" . ($rel[0]['followed_by'] ? "<span class='profileButton' width:290; height:25px; display:inline-block; margin-top:5px; style='background-color: rgba(255,255,255,.5);'>&#xe80c; Follows You</span>" : "") . "
						<div style='display:flex; width:280px'>";
						/*
						foreach ($photo as $elem){
							echo "<div style='overflow:hidden; display:block; height:90px; flex:1; background-image:url(\"".$elem['url']."\"); ".(isset($elem['s']) ? "filter: blur(5px);" : "")."  background-size:cover; margin:2px;'></div>";
						}
						*/
						echo "</div>
					</div>
				  ";
			die();
			break;
			
	case "previewpost":
			$post = api_get("statuses/".htmlentities($value));
			echo "<div class='notifContents' style='max-width:none;'>
				<div style='flex: 0 0 60px; background-size:cover; background-image:url(".$post['account']['avatar']."); border-radius:5px;'></div>
				<div style='flex: 1; padding-left:5px; padding-right:5px; word-break: break-all; overflow:hidden;'>
					<span><span style='font-size:12px; font-weight:bold;'><a class='link' style='font-size:12px;' href='?user=9hwsQhjN9oox1iSfK4'>".emojify($post['account']['display_name'],$post['account']['emojis'],20)."</a></span></span>
					<a style='text-decoration:none;' class='ldr' href='?thread=9nngbBWBRHvILwEoF6' target='_blank'><span style='display:block; opacity:1; font-size:10px; line-height:12px;'>".emojify(strip_tags($post['content'],'<br>'),$post['emojis'],20)."</span></a>
					</div>
					".(!empty($post['media_attachments']) ? "<div style='flex: 0 0 60px; background-size:cover; background-image:url(".$post['media_attachments'][0]['url'].");'></div>" :"")."
			</div>";
			die();
			break;
	
	
	case "themefile":
			echo themes("get",$value);
			die();
			break;
			
		case "themename":
			echo $user_settings['theme'];
			die();
			break;
			
	case "emoji":
		echo emoji_list(sanitize($value));
		break;

	case "contact":
		echo contact_search(sanitize($value));
		break;
	}

}


if(isset($_POST['status'])){
	
	if(isset($_POST['scope'])){
		switch($_POST['scope']){
			case "1":
			$scope = "public";
			break;
			
			case "2":
			$scope = "unlisted";
			break;
			
			case "3":
			$scope = "private";
			break;
			
			case "4":
			$scope = "direct";
			break;
		}
	} else {
		if (isset($_POST['thread'])){
			$result = api_get("statuses/".htmlentities($_POST['thread']));
			$scope = $result['visibility'];
		} else {
			$scope = "public";
		}
	}
	
	$uploaded = (empty($_POST['uploaded']) ? array() : explode("|",$_POST['uploaded']));
	$reply = json_decode(sendpost(trim($_POST['status']),$uploaded,$_POST['thread'],false,$scope,(isset($_POST['sensitive']) ? $_POST['sensitive'] : false),(isset($_POST['spoiler']) && $_POST['spoiler'] != 'Title (optional)' ? $_POST['spoiler'] : false)),true);
	echo render_reply($reply);
	die();
}


